package com.cloudkinto.service.statistics.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.appletservice.finance.vo.WxPayNotifyRequest;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.entity.NotificationDo;
import com.cloudkinto.dao.NotificationDao;
import com.cloudkinto.entity.OrderBackDo;
import com.cloudkinto.service.orderback.OrderBackService;
import com.cloudkinto.service.statistics.NotificationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.statistics.vo.NotificationItemRes;
import com.cloudkinto.service.statistics.vo.NotificationPageRes;
import com.cloudkinto.service.statistics.vo.RecordPageRes;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-06-19
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class NotificationServiceImpl extends ServiceImpl<NotificationDao, NotificationDo> implements NotificationService {
    @Autowired
    private NotificationDao dao;
    @Autowired
    private OrderBackService orderBackService;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        NotificationDo entityDo = new NotificationDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(NotificationDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(NotificationDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*NotificationDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(NotificationDo entityDo, Long userId) {
//        entityDo.setUpdateBy(userId);
//        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(NotificationDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        NotificationDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(NotificationDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public Object detail(Long id) {
        NotificationDo entityDo = dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<NotificationPageRes> getList(Map<String, String> map) {
        String userId = map.get("userId");
        QueryWrapper<NotificationDo> wrapper = queryBuild(map);
        List<NotificationDo> list = this.list(wrapper);
        List<NotificationPageRes> result = handlerListAfter(list, userId);
        return result;
    }

    @Override
    public SingleResult notificationNewest(Long userId) {
        Map map = new HashMap();
        LambdaQueryWrapper<NotificationDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(NotificationDo::getId);
        wrapper.last("limit 1");
        NotificationDo notificationDo = dao.selectOne(wrapper);
        if (notificationDo != null) {
            String readUserId = notificationDo.getReadUserId();
            if (StringUtils.isNotBlank(readUserId) && readUserId.contains(";")) {
                String[] strings = readUserId.split(";");
                List<String> stringList = Arrays.asList(strings);
                if (!stringList.contains(String.valueOf(userId))) {
                    map.put("id", notificationDo.getId());
                    map.put("isHasRead", 0);
                    map.put("content", notificationDo.getContent());
                } else {
                    map.put("isHasRead", 1);
                }
            } else {
                map.put("id", notificationDo.getId());
                map.put("isHasRead", 0);
                map.put("content", notificationDo.getContent());
            }
        }
        return SingleResult.success(map);
    }

    @Override
    public SingleResult confirmHavingRead(Long id, Long userId) {
        NotificationDo notificationDo = dao.selectById(id);
        if (notificationDo==null)return SingleResult.success();
        String readUserId = notificationDo.getReadUserId();
        if (StringUtils.isNotBlank(readUserId) && readUserId.contains(";")) {
            List<String> stringList = Arrays.asList(readUserId.split(";"));
            if (!stringList.contains(userId)) {
                readUserId = readUserId + userId + ";";
                notificationDo.setReadUserId(readUserId);
                dao.updateById(notificationDo);
            }
        } else {
            notificationDo.setReadUserId(userId + ";");
            dao.updateById(notificationDo);
        }
        return SingleResult.success();
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        String userId = map.get("userId");
        QueryWrapper<NotificationDo> wrapper = queryBuild(map);
        IPage<NotificationDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<NotificationPageRes> resList = handlerListAfter(page.getRecords(), userId);
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    @Override
    public List<NotificationPageRes> getListHomePageData(Map<String, String> map) {
        String userId = map.get("userId");
        QueryWrapper<NotificationDo> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last("limit 1");
        List<NotificationPageRes> resPage = new ArrayList<>();
        List<NotificationDo> list = dao.selectList(wrapper);
        NotificationPageRes res = new NotificationPageRes();
        if (list.size() > 0) {
            NotificationDo notificationDo = list.get(0);
            res.setId(notificationDo.getId());
            res.setContent(notificationDo.getContent());
            res.setCreateTime(notificationDo.getCreateTime());
            res.setTitle(notificationDo.getTitle());
            if (StringUtils.isNotBlank((userId))) {
                if (StringUtils.isNotBlank(notificationDo.getReadUserId()) && notificationDo.getReadUserId().contains(userId)) {
                    res.setIsRead(1);
                } else {
                    res.setIsRead(0);
                }
            }
            if (res.getIsRead() == 0) {
            resPage.add(res);
            }
        }
       //退货信息查询
       // List<OrderBackDo> orderBackDoList = orderBackService.getUnDealList(map.get("companyId"));
       // if (orderBackDoList.size() > 0) {
       //     List<NotificationItemRes> resItemList = new ArrayList<>();
       //     NotificationPageRes backRes = new NotificationPageRes();
       //     backRes.setIsRead(0);
       //     backRes.setContent(String.format("您有%d单退货订单即将超出最终保管日，即将废弃!请及时处理", orderBackDoList.size()));
       //     for (OrderBackDo orderBackDo : orderBackDoList) {
       //         NotificationItemRes itemRes = new NotificationItemRes();
       //         itemRes.setOrderNumber(orderBackDo.getTrackNumber());
       //         itemRes.setDays(TimeUtils.getBetweenDays(TimeUtils.formatDate(orderBackDo.getCreateTime(), "yyyy-MM-dd"), TimeUtils.getCurrentDateFormat(-4)));
       //         try {
       //             if (orderBackDo.getLastDate() != null)
       //                 itemRes.setDate(TimeUtils.formatDate(orderBackDo.getLastDate(), "MM-dd"));
       //         } catch (Exception e) {
       //             e.printStackTrace();
       //         }
       //         resItemList.add(itemRes);
       //     }
       //     backRes.setList(resItemList);
       //     resPage.add(backRes);
       // }
        return resPage;
    }

    //查询分页列表之后对列表数据的处理
    private List<NotificationPageRes> handlerListAfter(List<NotificationDo> list, String userId) {
        List<NotificationPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(notificationDo -> {
                NotificationPageRes res = new NotificationPageRes();
                res.setId(notificationDo.getId());
                res.setContent(notificationDo.getContent());
                res.setCreateTime(notificationDo.getCreateTime());
                res.setTitle(notificationDo.getTitle());
                if (StringUtils.isNotBlank((userId))) {
                    if (StringUtils.isNotBlank(notificationDo.getReadUserId()) && notificationDo.getReadUserId().contains(userId)) {
                        res.setIsRead(1);
                    } else {
                        res.setIsRead(0);
                    }
                }
                result.add(res);
            });
        }
        return result;
    }

    private IPage<NotificationDo> pageInit(Map<String, String> map) {
        IPage<NotificationDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 20);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<NotificationDo> queryBuild(Map<String, String> map) {
        QueryWrapper<NotificationDo> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        return wrapper;
    }
}
